//
//  HeadDetailView.m
//  carcareIOS
//
//  Created by tianxing on 16/3/10.
//  Copyright © 2016年 baozun. All rights reserved.
//

#define MAXVALUE       300.0f // 最大值

#define MAXOFFSETANGLE 105.0f
#define POINTEROFFSET  90.0f

#import "HeadDetailView.h"
#import "AVPlayerManager.h"
#import "UmengMgr.h"

#import <AVFoundation/AVFoundation.h>

@interface HeadDetailView()<UIGestureRecognizerDelegate>{
    
    CGFloat maxNum;
    CGFloat minNum;
    
    CGFloat maxAngle;
    CGFloat minAngle;
    
    CGFloat gaugeValue;
    CGFloat gaugeAngle;
    
    CGFloat angleperValue;
    CGFloat scoleNum;
    
    
    UIImageView    *_dashboardImageView;
    
    CGFloat      currentNum;
    
    CGFloat      pointNumBer;
    
}
@property (nonatomic ,strong) AVPlayerManager *AVPlayerManager;
@property (nonatomic ,strong) NSArray        *moneyArray;

@property (nonatomic ,strong) UILabel        *premiumNew;               // "今年保费"

@property (nonatomic ,strong) UILabel *premiumNumbers;           // 保费

@property (nonatomic ,strong) UILabel *remainingEarn;            // 剩余挣点

@property (nonatomic ,strong) UILabel        *tripInformL;              // 行程通知

@property (nonatomic ,strong) UIButton       *uploadButton;             // 上传保单

@property (nonatomic ,strong) UIButton       *uploadButtonImage;        // 上传保单的图片

@property (nonatomic ,strong) UIImageView    *animationIcon;            //金币图片

@property (nonatomic ,strong) UIImageView     *pointer;                  //指针图片

@property (nonatomic ,assign) CGFloat         lineHeight;                //线的高度

@property (nonatomic ,strong) NSTimer         *timer;                    //定时器

@property (nonatomic ,strong) UIImageView     *icons;                    //一大堆金币

@property (nonatomic, strong) AVPlayer *avPlayer;

@end

@implementation HeadDetailView

- (void)dealloc{
    self.timer = nil;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpView];
    }
    return self;
}

- (void)setUpView{
    __weak __typeof(self) wself = self;
    // 仪表板
    CGFloat dashWidth = __MAIN_WIDTH - 88 * __MAIN_RATIO_375;
    _dashboardImageView = [Factory imageViewWithFrame:CGRectMake(44 * __MAIN_RATIO_375, 30 *__MAIN_RATIO_375, dashWidth, 155 * __MAIN_RATIO_375) image:ImageNamed(@"Home_dashboard") onView:self];
    _dashboardImageView.contentMode = UIViewContentModeScaleToFill;
    
    // 设置仪表盘位置  半径为155
    CGFloat R = _dashboardImageView.width/2 - 32 * __MAIN_RATIO_375;
    for (NSInteger i = 0; i < 5; i ++) {
        UILabel *money = [Factory labelWithFrame:CGRectMake(
                                                            (_dashboardImageView.centerX - R  * cos(45 * i * M_PI / 180) - 23 * __MAIN_RATIO_375),
                                                            (_dashboardImageView.bottom - R * sin(45 * i * M_PI / 180) - 14 * __MAIN_RATIO_375 - (i == 2 ? 8 * __MAIN_RATIO_375 : 0)) ,
                                                            23 * __MAIN_RATIO_375,
                                                            15 * __MAIN_RATIO_375)
                                            font:FONT_DEFAULT_Light(10) text:self.moneyArray[i] textColor:COLOR_HEXSTRING(@"#949494") onView:self textAlignment:NSTextAlignmentRight];
        UILabel *yuan = [Factory labelWithFrame:CGRectMake(money.right, 0, 10 * __MAIN_RATIO_375, 15 * __MAIN_RATIO_375) font:FONT_DEFAULT_Light(8) text:@"元" textColor:COLOR_HEXSTRING(@"#949494") onView:self textAlignment:NSTextAlignmentLeft];
        money.tag = 110 + i;
        yuan.bottom = money.bottom;
    }
    [self setPointerView];
    
    self.icons = [Factory imageViewWithCenter:CGPointMake(self.centerX, _dashboardImageView.bottom - 25) image:ImageNamed(@"Home_icons") onView:self];
    self.icons.hidden = YES;
    // 数据数字 （例如126.5）
    self.deductibleInsuranceLabel = [[UICountingLabel alloc] initWithFrame:CGRectMake(0, _dashboardImageView.bottom +5, 200 * __MAIN_RATIO_375, 40)];
    self.deductibleInsuranceLabel.font = FONT_DEFAULT_Light(45 * __MAIN_RATIO_375);
    self.deductibleInsuranceLabel.textAlignment = NSTextAlignmentCenter;
    self.deductibleInsuranceLabel.format = @"%0.1f";
//    self.premiumNumbers.method = UILabelCountingMethodEaseInOut;
    self.deductibleInsuranceLabel.centerX = self.centerX;
    [self addSubview:self.deductibleInsuranceLabel];
    
    // 可抵扣保费的说明  【首页】修改：可抵扣保费（元）修改为 可抵扣 
    UILabel *deductionDetail = [Factory labelWithFrame:CGRectMake(135 * __MAIN_RATIO_375, self.deductibleInsuranceLabel.bottom, 110, 30) font:FONT_DEFAULT_Light(14) text:[UmengMgr titleByKey:@"homepage_can_pay"] textColor:COLOR_HEXSTRING(@"#CCCCCCC") onView:self textAlignment:NSTextAlignmentCenter];
    deductionDetail.centerX = self.centerX;
    deductionDetail.numberOfLines = 1;
    // 问好图标
//    UIButton *buttonDetail = [Factory buttonWithCenter:CGPointMake(0, deductionDetail.centerY) withImage:ImageNamed(@"Home_deductionDetail") click:^{
//    // 跳转界面
//        wself.JumpClick();
//    } onView:self];
//    buttonDetail.left =  deductionDetail.right;
    
    // 今年保费
    self.premiumNumbers = [[UILabel alloc] initWithFrame:CGRectMake(44 * __MAIN_RATIO_375,_dashboardImageView.bottom + 85 , 65 * __MAIN_RATIO_375, 15 )];
    self.premiumNumbers.font = FONT_DEFAULT_Light(18);
//    self.premiumNumbers.method = UILabelCountingMethodEaseInOut;
//    self.premiumNumbers.format = @"%.0d";
    self.premiumNumbers.numberOfLines = 1;
    self.premiumNumbers.hidden = YES;
    self.premiumNumbers.textColor = COLOR_HEXSTRING(@"#99999a");
    self.premiumNumbers.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.premiumNumbers];
    
    
    self.premiumNew = [Factory labelWithFrame:CGRectMake(0, self.premiumNumbers.bottom + 10 , 60 * __MAIN_RATIO_375, 15) font:FONT_DEFAULT_Light(12) text:[UmengMgr titleByKey:@"homepage_year_money"] textColor:COLOR_HEXSTRING(@"#6a6a6a") onView:self textAlignment:NSTextAlignmentCenter];
    self.premiumNew.centerX = self.premiumNumbers.centerX;
    self.premiumNew.hidden = YES;
    
    // 今年保费中的button上传事件 (字体)
    self.uploadButton = [[UIButton buttonWithFrame:CGRectMake(0, self.premiumNumbers.bottom + 12 , 120 * __MAIN_RATIO_375, 15) title:@"" textColor:nil font:FONT_BUTTON click:nil] setupOnView:self];
    
    [self.uploadButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.uploadButton.titleLabel.font  = FONT_DEFAULT_Light(12);
    [self.uploadButton addTarget:self action:@selector(upLoad:) forControlEvents:UIControlEventTouchUpInside];
    self.uploadButton.centerX = self.premiumNumbers.centerX;
    [self.uploadButton setTitleColor:COLOR_HEXSTRING(@"#6a6a6a") forState:UIControlStateNormal];
    
    // 图片
    self.uploadButtonImage = [[UIButton buttonEmptyWithFrame:CGRectMake(44 * __MAIN_RATIO_375,_dashboardImageView.bottom + 80, 65 * __MAIN_RATIO_375, 25 ) click:^{}] setupOnView:self];
    self.uploadButtonImage.backgroundColor = [UIColor clearColor];
    [self.uploadButtonImage addTarget:self action:@selector(upLoad:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 剩余挣点
    self.remainingEarn = [[UILabel alloc] initWithFrame:CGRectMake(0,_dashboardImageView.bottom + 85 , 70 * __MAIN_RATIO_375, 15 )];
    self.remainingEarn.font = FONT_DEFAULT_Light(18);
//    self.remainingEarn.format = @"%.0f";
//    self.remainingEarn.method = UILabelCountingMethodEaseInOut;
    self.remainingEarn.textColor = COLOR_HEXSTRING(@"#99999a");
    self.remainingEarn.textAlignment = NSTextAlignmentCenter;

    [self addSubview:self.remainingEarn];
    self.remainingEarn.right = self.right - 42 * __MAIN_RATIO_375;
    
    
    UILabel *labelRemain = [Factory labelWithFrame:CGRectMake(0, self.remainingEarn.bottom + 10, 60 *__MAIN_RATIO_375, 15) font:FONT_DEFAULT_Light(12) text:@"剩余挣点" textColor:COLOR_HEXSTRING(@"#6a6a6a") onView:self textAlignment:NSTextAlignmentCenter];
    labelRemain.centerX = self.remainingEarn.centerX;
    
    UIButton *remainBT = [[UIButton buttonEmptyWithFrame:CGRectMake(0,_dashboardImageView.bottom + 85 , 70 * __MAIN_RATIO_375, 40) click:nil] setupOnView:self];
    [remainBT addTarget:self action:@selector(JumpRemain:) forControlEvents:UIControlEventTouchUpInside];
    remainBT.backgroundColor = [UIColor clearColor];
    remainBT.centerX = self.remainingEarn.centerX;
    self.FinishAnimation = ^(){
        wself.timer= [NSTimer scheduledTimerWithTimeInterval:0.2 target:wself selector:@selector(run) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:wself.timer forMode:NSRunLoopCommonModes];
        [wself music];
        [wself performSelector:@selector(reloadPointAnimation) withObject:nil afterDelay:2];
        [wself performSelector:@selector(delayPointAnimation) withObject:nil afterDelay:1.8];
    };
    
}
- (void)delayPointAnimation{
    
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark --- 设置指针
- (void)setPointerView{
    currentNum = 0;
    scoleNum = _dashboardImageView.width/__MAIN_WIDTH;
    minNum = 0;
    minAngle = -MAXOFFSETANGLE;
    maxAngle = MAXOFFSETANGLE;
    gaugeValue = 0;
    gaugeAngle = -MAXOFFSETANGLE;
    angleperValue = (maxAngle - minAngle)/(maxNum - minNum);
    //添加指针
    UIImage *homePointer = [UIImage imageNamed:@"Home_pointter"];
    self.pointer = [[UIImageView alloc] initWithImage:homePointer];
    self.pointer.tag = 100;
    self.pointer.height = _dashboardImageView.width / 2;
    self.pointer.layer.anchorPoint = CGPointMake(0.5, 0.78);
    self.pointer.center = CGPointMake(_dashboardImageView.centerX + 2 *__MAIN_RATIO_375, _dashboardImageView.centerY + 40 * __MAIN_RATIO_375);
    self.pointer.transform = CGAffineTransformMakeScale(scoleNum, scoleNum);
    [self addSubview:self.pointer];
    self.pointer.layer.transform = CATransform3DMakeRotation(MAXOFFSETANGLE, 0, 0, 1);
    
}
#pragma mark --- 上传
- (void)upLoad:(UIButton *)sender{
    
    if (self.UploadClick) {
        self.UploadClick(sender);
    }
}
- (void)JumpRemain:(UIButton *)sender{
    
    if (self.JumpRemainMoney) {
        self.JumpRemainMoney();
    }
}
#pragma mark --- 定时器
- (void)run{
    [self iconAnimation];
}
- (void)music{
    // 音乐
    [self.avPlayer play];
}

-(AVPlayer *)avPlayer{
    if (!_avPlayer) {
        
        NSString *Path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"mp3"];
        NSURL *Url = [NSURL fileURLWithPath:Path];
        AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:Url];
        _avPlayer = [AVPlayer playerWithPlayerItem:item];
    }
    return _avPlayer;
}

#pragma mark --- 金币动画
- (void)iconAnimation{
    
    //金币
    self.animationIcon = [Factory imageViewWithFrame:CGRectMake(self.center.x - 20 *__MAIN_RATIO_375 +- arc4random()%30, _dashboardImageView.top, 20, 20) image:ImageNamed(@"Home_icon") onView:self];
    self.animationIcon.hidden = YES;
    self.animationIcon.tag = 10;
    self.icons.hidden = NO;
    __weak typeof(self) wself = self;
    
    [UIView animateWithDuration:5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:3 options:UIViewAnimationOptionOverrideInheritedCurve animations:^{
            wself.animationIcon.hidden = NO;
            wself.animationIcon.center = CGPointMake(_dashboardImageView.centerX - 10 *__MAIN_RATIO_375 +- arc4random()%30, _dashboardImageView.bottom - 10 * __MAIN_RATIO_375);
            wself.animationIcon.size = CGSizeMake(5, 5);
            wself.animationIcon.alpha = 0.1;
        } completion:^(BOOL finished) {
            wself.icons.hidden = YES;
            wself.animationIcon.hidden = YES;
    }];
}
- (void)reloadPointAnimation{
    self.animationIcon.hidden = YES;
    self.icons.hidden = YES;
    for (UIView *view in self.subviews) {
        if (view.tag == 10) {
            [view removeFromSuperview];
        }
    }
}
#pragma mark --- 指针的方法集

-(void)setGaugeValue:(CGFloat)value animation:(BOOL)isAnim
{
    CGFloat tempAngle = [self parseToAngle:value];
    gaugeValue = value;
    //设置转动时间和转动动画
    __weak typeof(self) wself = self;
        if(isAnim){
            [wself pointToAngle:tempAngle Duration:1.5];
        }else
        {
            [wself pointToAngle:tempAngle Duration:0.0f];
        }
}
- (void) pointToAngle:(CGFloat) angle Duration:(CGFloat) duration
{
    CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"transform"];
    NSMutableArray *values=[NSMutableArray array];
    anim.duration = duration;
    anim.autoreverses = NO;
    anim.fillMode = kCAFillModeForwards;
    anim.removedOnCompletion= NO;
    CGFloat distance = angle/30;
    //设置转动路径，不能直接用 CABaseAnimation 的toValue，那样是按最短路径的，转动超过180度时无法控制方向
    int i = 1;
    for(;i<=30;i++){
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle + distance*i)], 0, 0, 1)]];
    }
    //添加缓动效果
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle + distance*(i))], 0, 0, 1)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle + distance*(i-2))], 0, 0, 1)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle + distance*(i-1))], 0, 0, 1)]];
    anim.values=values;
    
    [self.pointer.layer addAnimation:anim forKey:@"cubeIn"];
    
    self.pointer.layer.timeOffset = 0;
    
    gaugeAngle = gaugeAngle + angle;
}

-(CGFloat)transToRadian:(CGFloat)angel
{
    return angel*M_PI/180;
}

- (CGFloat) parseToX:(CGFloat) radius Angle:(CGFloat)angle
{
    CGFloat tempRadian = [self transToRadian:angle];
    return radius*cos(tempRadian);
}

- (CGFloat) parseToY:(CGFloat) radius Angle:(CGFloat)angle
{
    CGFloat tempRadian = [self transToRadian:angle];
    return radius*sin(tempRadian);
}

-(CGFloat) parseToAngle:(CGFloat) val
{
    //异常的数据
    if(val < minNum){
        return minNum;
    }else if(val > maxNum){
        return maxNum;
    }
    CGFloat temp =(val-gaugeValue)*angleperValue;
    return temp;
    
}
-(CGFloat) parseToValue:(CGFloat) val
{
    CGFloat temp=val/angleperValue;
    CGFloat temp2=maxNum/2+temp;
    if(temp2>maxNum){
        return maxNum;
    }else if(temp2<maxNum){
        return maxNum;
    }
    return temp2;
}

#pragma mark --- setter ang getter

- (void)setPremium:(NSInteger)premium{
    _premium = premium;
    if ([self.premiumNumbers.text intValue] == premium) {
        return;
    }
    self.premiumNumbers.text = [NSString stringWithFormat:@"%.0ld",(long)premium];
    
//    [self.premiumNumbers countFromCurrentValueTo:premium withDuration:0];
}
- (void)setRemainEarn:(NSInteger)remainEarn{
    _remainEarn = remainEarn;
    if ([self.remainingEarn.text intValue] == remainEarn && self.remainEarn != 0) {
        return;
    }
    self.remainingEarn.text = [NSString stringWithFormat:@"%zd",remainEarn];
//    [self.remainingEarn countFromCurrentValueTo:remainEarn withDuration:0];
}
- (void)setTotalScoreMoney:(CGFloat)totalScoreMoney{
    
    if (totalScoreMoney <= 0) {
        maxNum = 200;
    }else {
      maxNum = totalScoreMoney;
    }
    angleperValue = (maxAngle - minAngle)/(maxNum - minNum);
    
    for (int i = 0; i < 5; i++) {
        UILabel *label = [self viewWithTag:110+i];
        label.text = self.moneyArray[i];
    }
}

- (NSArray *)moneyArray{
    NSString *string1 = [self setTotalToString:0];
    NSString *string2 = [self setTotalToString:maxNum * 0.25];
    NSString *string3 = [self setTotalToString:maxNum * 0.5];
    NSString *string4 = [self setTotalToString:maxNum * 0.75];
    NSString *string5 = [self setTotalToString:maxNum];
    NSArray *array = [NSArray arrayWithObjects:string1,string2,string3,string4,string5,nil];
    return array;
}

- (NSString *)setTotalToString:(CGFloat)total{
    int to = total;
    NSString *string = [NSString stringWithFormat:@"%d",to];
    return string;
}

- (void)setCurrScoreModey:(CGFloat)currScoreModey{
    int a ;
    a = floor(currScoreModey * 10);
    CGFloat b = a * 0.1;
    
    if (currentNum != b) {
        currentNum = b;
        [self.deductibleInsuranceLabel countFromCurrentValueTo:b withDuration:3];
        [self setGaugeValue:currentNum animation:YES];
    }
    
}

- (void)setStatus:(NSInteger)status{
    
    if (status == 3) {
        [self.uploadButton setTitle:[UmengMgr titleByKey:@"homepage_upload_image"] forState:UIControlStateNormal];
        [self.uploadButton setTitleColor:COLOR_HEXSTRING(@"#6a6a6a") forState:UIControlStateNormal];
        [self.uploadButtonImage setImage:ImageNamed(@"Home_add1") forState:UIControlStateNormal];
    }else if (status == 4){
        self.uploadButton.enabled = NO;
        self.uploadButtonImage.enabled = NO;
        [self.uploadButtonImage setImage:ImageNamed(@"Home_whide") forState:UIControlStateNormal];
        [self.uploadButton setTitle:@"正在审核" forState: UIControlStateNormal];
        [self.uploadButton setTitleColor:COLOR_HEXSTRING(@"#6a6a6a") forState:UIControlStateNormal];
        
    }else if (status == 2){
        [self.uploadButton setTitle:@"审核未通过" forState: UIControlStateNormal];
        [self.uploadButton setTitleColor:COLOR_HEXSTRING(@"#ff672d") forState:UIControlStateNormal];
        self.uploadButtonImage.enabled = YES;
        self.uploadButton.enabled = YES;
        [self.uploadButtonImage setImage:ImageNamed(@"Home_add1") forState:UIControlStateNormal];
        
    }else if (status == 1) {
        self.premiumNumbers.hidden = NO;
        self.premiumNew.hidden = NO;
        self.uploadButton.enabled = NO;
        self.uploadButtonImage.enabled =NO;
        self.uploadButton.hidden = YES;
        self.uploadButtonImage.hidden= YES;
        [self.uploadButton setTitle:@"" forState:UIControlStateNormal];
        self.uploadButtonImage.backgroundColor = [UIColor clearColor];
        self.uploadButton.backgroundColor = [UIColor clearColor];
        
        self.premiumNumbers.text = [NSString stringWithFormat:@"%.0ld",(long)self.premium];
    }
}
+ (CGFloat)heightForView{
    
    return ViewHeight;
    
}
@end
